<template>
  <view class="page">
    <view class="box">
      <view class="box-1 flex">
        <view class="box-1-1">提货人</view>
        <input type="text" v-model="consignee" />
      </view>
      <view class="box-1 flex" style="border: none;">
        <view class="box-1-1">手机号</view>
        <input type="number" v-model="phone" />
      </view>
    </view>
    <view class="shop-box" v-for="(caritem, carindex) in cartData" :key="carindex">
      <view class="shop-1" @tap="allcheckTap(carindex)">
        <view class="titile">{{ caritem.storename }}
        </view>
      </view>
      <view class="shop-con" v-for="(carvalue, valindex) in caritem.datalist" :key="valindex">
        <image :src="showImgApi + carvalue.img" class="shop_img2" />
        <view class="right">
          <view class="shop-title">{{ carvalue.title }}</view>
          <view class="flex" style="margin-top: 80rpx;justify-content: space-between;">
            <view class="price"><span>￥</span>{{ carvalue.price }}</view>
            <view class="bottom">
              <!-- <view class="reduce" @tap="numchangeTap('minus',carindex,valindex)">-</view> -->
              <view class="num">×{{ carvalue.number }}</view>
              <!-- <view class="reduce add" @tap="numchangeTap('add',carindex,valindex)">+</view> -->
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="kong"></view>
    <view class="flex-box flex">
      <view class="flex-1">需支付：<span>￥{{ totalPriceSum }}</span></view>
      <view class="flex-btn" @click="handleSubOrder">提交订单</view>
    </view>
  </view>
</template>
<script>
import {
  submitOrder, handleBuy, orderPay
} from '@/utils/request.js'
export default {
  data() {
    return {
      cartData: [],
      showImgApi: this.$config.showImgApi,
      totalPriceSum: 0,
      consignee: '',
      phone: '',
      ids: '',
      order_type: '',
      product_id: '',
      product_type: ""
    }
  },
  onLoad(option) {
    console.log(option, 'option')
    const data = { order_type: option.order_type }
    this.order_type = option.order_type
    const userInfo = JSON.parse(uni.getStorageSync('userInfo'))
    this.consignee = userInfo.username
    this.phone = userInfo.phone
    let totalPriceSum = 0;
    if (option.order_type === '1') {
      this.ids = JSON.parse(option.ids)
      data.ids = JSON.parse(option.ids)
    } else {
      data.product_id = option.product_id
      this.product_id = option.product_id
      data.product_type = option.product_type
      this.product_type = option.product_type
    }
    this.submitOrder(data).then(res => {
      this.cartData = res.list.reduce((acc, cur) => {
        // 查找当前类型是否已经在accumulator中存在
        var existingGroup = acc.find(group => group.storename === cur.type_title);
        totalPriceSum += parseFloat(cur.total_price);
        if (existingGroup) {
          // 如果存在，添加到已有的group中
          existingGroup.datalist.push({
            'img': cur.img,
            'title': cur.title,
            'number': cur.num,
            'price': parseFloat(cur.people_price)
          });
        } else {
          // 如果不存在，创建一个新的group并确保datalist是一个数组
          acc.push({
            'storename': cur.type_title,
            'datalist': [{
              'img': cur.img,
              'title': cur.title,
              'number': cur.num,
              'price': parseFloat(cur.people_price)
            }]
          });
        }
        return acc;
      }, []); // 确保初始值为空数组
      this.totalPriceSum = totalPriceSum.toFixed(2)
    })
  },
  methods: {
    async submitOrder(data) {
      return await submitOrder(data)
    },
    async handleBuy(data) {
      return await handleBuy(data)
    },
    async orderPay(data) {
      return await orderPay(data)
    },

    handleSubOrder() {
      const data = { order_type: this.order_type, user_id: JSON.parse(uni.getStorageSync('userInfo')).id, consignee: this.consignee, phone: this.phone, address: '陕西省西安市新城区' }
      if (this.order_type === '1') {
        data.ids = this.ids
      } else {
        data.product_id = this.product_id
        data.product_type = this.product_type
        data.num = 1
      }
      this.handleBuy(data).then(res => {
        // #ifdef H5
        const date = { id: res.order_id, platform: 1 }
        // #endif
        // #ifdef MP-WEIXIN
        const date = { id: res.order_id, platform: 2 }
        // #endif
        this.orderPay(date).then(res => {
          console.log(res, 'res')
          // #ifdef MP-WEIXIN
          if (res) {
            uni.requestPayment({
              timeStamp: res.timeStamp,
              nonceStr: res.nonceStr,
              package: res.package,
              signType: res.signType,
              paySign: res.paySign,
              success: (res) => {
                uni.showToast({
                  title: "支付成功",
                  icon: "none",
                });
                setTimeout(() => {
                  uni.navigateBack({ delta: 2 });
                }, 1500);
              },
              faile: (err) => {
                if (err.errMsg === 'requestPayment:fail cancel') {
                  console.log('用户取消了支付');
                  // 用户取消支付后的逻辑处理
                } else {
                  console.error('支付失败', err);
                  // 其他支付失败原因的处理
                }
              },
            });
          }
          // #endif
          // #ifdef H5
          if (res) {
            uni.requestPayment({
              provider: "wxpay",
              orderInfo: {
                appid: res.appId,
                noncestr: res.nonceStr,
                package: res.package,
                // partnerid: "148*****52",
                // prepayid: "wx202254********************fbe90000", // 统一下单订单号
                timestamp: res.timeStamp, // 时间戳（单位：秒）
                sign: res.signType, // 签名，这里用的 MD5/RSA 签名
              },
              success: (res) => {
                uni.showToast({
                  title: "支付成功",
                  icon: "none",
                });
                setTimeout(() => {
                  uni.navigateBack({ delta: 2 });
                }, 1500);
              },
              faile: (err) => {
                console.log(err, "err");
              },
            });
          }
          // #endif
        })
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.shop-box {
  width: 706rpx;
  padding: 22rpx 0 42rpx;
  background: #ffffff;
  border-radius: 20rpx;
  margin: 24rpx auto 0;
}

.kong {
  width: 100%;
  height: 200rpx;
}

.shop-1 {
  width: 95%;
  margin: 0 auto;
  display: flex;
  align-items: center;
}

.flex-box {
  width: 100%;
  height: 120rpx;
  line-height: 120rpx;
  display: flex;
  align-items: center;
  position: fixed;
  justify-content: space-between;
  bottom: 0rpx;
  right: 0;
  background: #ffffff;

  .flex-1 {
    font-size: 28rpx;
    color: rgb(131, 131, 131);
    margin-left: 32rpx;

    span {
      font-size: 32rpx;
      color: rgb(255, 184, 80);
    }
  }

  .flex-btn {
    width: 262rpx;
    height: 73rpx;
    line-height: 73rpx;
    margin-right: 28rpx;
    font-size: 30rpx;
    color: #ffffff;
    background: rgb(255, 184, 80);
    border-radius: 36rpx;
    text-align: center;
  }
}

.titile {
  font-size: 26rpx;
  display: flex;
  align-items: center;

  view {
    display: block;
    margin-left: 14rpx;
    font-size: 16rpx;
    color: #d7d7d7;
  }
}

.shop-con {
  width: 95%;
  margin: 26rpx auto 0;
  display: flex;
  align-items: center;
}

.shop_img1 {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.shop_img2 {
  width: 180rpx;
  height: 180rpx;
  border-radius: 16rpx;
}

.right {
  // width: 390rpx;
  flex: 1;
  height: 180rpx;
  margin-left: 20rpx;
  margin-top: 10rpx;
}

.shop-title {
  display: flex;
  justify-content: space-between;
  font-size: 28rpx;
}

.kuan {
  width: 120rpx;
  height: 46rpx;
  line-height: 46rpx;
  background: #fafafa;
  border-radius: 10rpx;
  color: #9e9e9e;
  text-align: center;
}

.page {
  padding-top: 16rpx;
}

.box {
  width: 694rpx;
  border-radius: 22rpx;
  margin: 0 auto;
  background: #ffffff;
  border-radius: 22rpx;

  .box-1 {
    padding: 32rpx 0;
    border-bottom: 1rpx solid rgb(133, 133, 133);
    width: 637rpx;
    margin: 0 auto;
    justify-content: space-between;
    font-size: 25rpx;

    input {
      text-align: right;
    }
  }
}
</style>